package cevent.source.cloudcenter.server.service;

import cevent.source.cloudcenter.server.domain.Article;
import cevent.source.cloudcenter.server.domain.ArticleExample;
import cevent.source.cloudcenter.server.dto.*;
import cevent.source.cloudcenter.server.enums.*;
import cevent.source.cloudcenter.server.mapper.ArticleMapper;
import cevent.source.cloudcenter.server.util.DuplicateUtil;
import cevent.source.cloudcenter.server.util.UUID8Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author cevent
 * @description 文章/产品表服务层
 */
@Service
public class ArticleService {

    private static final Logger LOG = LoggerFactory.getLogger(AssertionError.class);

    @Resource
    private ArticleMapper articleMapper;
    //调用moduleMapper
    @Resource
    private ModuleService moduleService;

    //1.无分页列表查询：dto获取domain参数
    public List<ArticleDto> articleDtoList() {
        ArticleExample articleExample = new ArticleExample();
        articleExample.setOrderByClause("uni_id asc");
        List<Article> articleList = articleMapper.selectByExample(articleExample);
        List<ArticleDto> articleDtoList = new ArrayList<ArticleDto>();
        for (int i = 0; i < articleList.size(); i++) {
            Article article = articleList.get(i);
            ArticleDto articleDto = new ArticleDto();
            //复制拷贝(source,target)
            BeanUtils.copyProperties(article, articleDto);
            articleDtoList.add(articleDto);
        }
        return articleDtoList;
    }

    /*2.分页查询：pageDto保存数据
        list数据集合：listPageData
        当前页码：currentPage
        每页行数：size
        总计函数：totalSize
        前端可返回pageDto，无需返回值
        ** 使用articlePageDto，继承pageDto，加入moduleId
     */
    public void getArticlePageDtoList(ArticlePageDto articlePageDto) {
        //1.分页设置（前端传入当前页和每页行数params），起始页，每页行数size
        PageHelper.startPage(articlePageDto.getCurrentPage(), articlePageDto.getSize());

        ArticleExample articleExample = new ArticleExample();
        //**根据moduleId查询article
        //注意：createCriterial只能使用一次，如果多次，需要在外层定义
        ArticleExample.Criteria criteria = articleExample.createCriteria();
        if (!StringUtils.isEmpty(articlePageDto.getModuleId())) {
            criteria.andModuleIdEqualTo(articlePageDto.getModuleId());
        }
        articleExample.setOrderByClause("sort asc");

        List<Article> articleList = articleMapper.selectByExampleWithBLOBs(articleExample);
        //2.将mapper查询结果复制到pageInfo
        PageInfo<Article> pageInfo = new PageInfo<>(articleList);
        //3.pageInfo计算处理处理=>后分页的总行数set到pageDto做记录
        articlePageDto.setTotalSize(pageInfo.getTotal());

        List<ArticleDto> articleDtoList = new ArrayList<>();
        articleList.stream().forEach(article -> {
            //更新seoKey
            List<String> seoKey = Arrays.asList(article.getSeoKeyword().split(";"));
            List<String> pics = Arrays.asList(article.getPicList().split(";"));
            ArticleDto articleDto = new ArticleDto();
            BeanUtils.copyProperties(article, articleDto);
            articleDto.setSeoKeyword(seoKey);
            articleDto.setPicList(pics);
            articleDtoList.add(articleDto);
        });

        articlePageDto.setListPageData(articleDtoList);

    }

    /**
     * 这里由于联动了两张表的数据，需要加事务
     * 3.新增、修改article，将传入的id转为article对象本身
     */
    @Transactional
    public void save(ArticleModuleDto articleModuleDto) {
        //转换seoKey
        List<String> seoKey = articleModuleDto.getSeoKeyword();
        StringBuilder sb = new StringBuilder();
        for (String item : seoKey) {
            sb.append(item + ";");
        }
        String seoKeyword = sb.toString();
        List<String> pics = articleModuleDto.getPicList();
        StringBuilder sbu = new StringBuilder();
        for (String item : pics) {
            sbu.append(item + ";");
        }
        String picList = sbu.toString();

        Article article = DuplicateUtil.copy(articleModuleDto, Article.class);
        article.setSeoKeyword(seoKeyword);
        article.setPicList(picList);
        if (StringUtils.isEmpty(articleModuleDto.getUniId())) {
            this.insert(article);
        } else {
            this.update(article);
        }

        //调用更新videoTime方法,先更新moduleSub
        LOG.info("------》article传入的articleModule结果：{}", articleModuleDto);
        //moduleService.updateModuleSubVideoTime(articleModuleDto.getModuleId());
        //moduleService.updateModuleVideoTime(articleModuleDto.getModuleId(),articleModuleDto.getModuleUniId());
        LOG.info("---->传入的moduleUniId：{}", articleModuleDto.getModuleUniId());
        //moduleService.updateMduleTime(articleModuleDto.getModuleUniId());
    }

    //7.保存图片
    public List<String> savePicList(ModulePicPathDto modulePicPathDto) {
        //根据moduleId获取article
        Article article = articleMapper.selectByPrimaryKey(modulePicPathDto.getModuleId());
        List<String> picList = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        //article.picList不为空，存储stringBuilder
        if (!StringUtils.isEmpty(article.getPicList())) {
            picList = Arrays.asList(article.getPicList().split(";"));
            for (String pic : picList) {
                sb.append(pic + ";");
            }
        }
        //将dto传入的picPath放入sb
        sb.append(modulePicPathDto.getPicPath());
        //将stringBuilder转为string存入数据库
        String pic = sb.toString();
        article.setPicList(pic);
        articleMapper.updateByPrimaryKeyWithBLOBs(article);
        //更新完毕，返回pics
        List<String> pics = getPicList(modulePicPathDto.getModuleId());
        return pics;

    }

    private List<String> getPicList(String moduleId) {
        Article article = articleMapper.selectByPrimaryKey(moduleId);
        List<String> pics = Arrays.asList(article.getPicList().split(";"));
        return pics;
    }

    //4.删除模块
    public void delete(String uniId) {
        ArticleExample articleExample = new ArticleExample();
        articleMapper.deleteByPrimaryKey(uniId);
    }

    //5.向外暴露dto，不暴露实体类：插入数据
    private void insert(Article article) {
        article.setUniId(UUID8Util.getShortUUID());
        if (article.getModuleId() == null) {
            article.setModuleId("0");
        }
        if (article.getVideoCharge() == null) {
            article.setVideoCharge(VideoChargeEnum.FREE.getCode());
        }

        if (article.getTypeId() == null) {
            article.setTypeId(ArticleTypeEnum.ARTICLE_OTHER.getCode());
        }
        if (article.getLevel() == null) {
            article.setLevel(LevelEnum.ONE.getCode());
        }
        if (article.getPrice() == null) {
            article.setPrice(BigDecimal.valueOf(0));
        }
        try {
            Date now = new Date();
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
            long time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date).getTime();
            int timeInt = (int) (time / 1000);
            article.setCreateTime(now);
            article.setUpdateTime(now);
            article.setiCreateTime(timeInt);
            article.setiUpdateTime(timeInt);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //普通insert不能实现longText类型数据更新
        articleMapper.insertSelective(article);
    }

    //6.更新模块
    private void update(Article article) {
        try {
            Date now = new Date();
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
            long time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date).getTime();
            int timeInt = (int) (time / 1000);

            article.setUpdateTime(now);
            article.setiUpdateTime(timeInt);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //longText类型数据，需要selective
        articleMapper.updateByPrimaryKeySelective(article);
    }

    //7.获取全部文章列表
    public void getArticleDtoList(PageDto pageDto) {
        PageHelper.startPage(pageDto.getCurrentPage(), pageDto.getSize());
        ArticleExample articleExample = new ArticleExample();
        ArticleExample.Criteria criteria = articleExample.createCriteria();
        criteria.andIsShowEqualTo(YesOrNoEnum.YES.getCode());
        criteria.andStatusEqualTo(StatusEnum.PUBLISH.getCode());
        articleExample.setOrderByClause("sort desc");
        List<Article> articleList = articleMapper.selectByExampleWithBLOBs(articleExample);
        //查询结果放入pageINFO
        PageInfo<Article> pageInfo = new PageInfo<>(articleList);
        //pageinfo计算总条数
        pageDto.setTotalSize(pageInfo.getTotal());

        List<ArticleDto> articleDtoList = new ArrayList<>();
        articleList.stream().forEach(article -> {
            List<String> seoKey = Arrays.asList(article.getSeoKeyword().split(";"));
            List<String> picList = Arrays.asList(article.getPicList().split(";"));
            ArticleDto articleDto = DuplicateUtil.copy(article, ArticleDto.class);
            articleDto.setSeoKeyword(seoKey);
            articleDto.setPicList(picList);
            articleDtoList.add(articleDto);
        });
        pageDto.setListPageData(articleDtoList);
    }

    //8.根据文章类型获取文章列表
    public void getArticlePageList(PageSelectDto pageSelectDto) {
        PageHelper.startPage(pageSelectDto.getCurrentPage(), pageSelectDto.getSize());
        ArticleExample articleExample = new ArticleExample();
        ArticleExample.Criteria criteria = articleExample.createCriteria();
        criteria.andIsShowEqualTo(YesOrNoEnum.YES.getCode());
        criteria.andStatusEqualTo(StatusEnum.PUBLISH.getCode());
        criteria.andTypeIdEqualTo(pageSelectDto.getTypeId());
        articleExample.setOrderByClause("sort desc");
        List<Article> articleList = articleMapper.selectByExampleWithBLOBs(articleExample);
        PageInfo<Article> pageInfo = new PageInfo<>(articleList);
        pageSelectDto.setTotalSize(pageInfo.getTotal());

        List<ArticleDto> articleDtoList = new ArrayList<>();
        articleList.stream().forEach(article -> {
            List<String> seoKey = Arrays.asList(article.getSeoKeyword().split(";"));
            List<String> picList = Arrays.asList(article.getPicList().split(";"));
            ArticleDto articleDto = DuplicateUtil.copy(article, ArticleDto.class);
            articleDto.setSeoKeyword(seoKey);
            articleDto.setPicList(picList);
            articleDtoList.add(articleDto);
        });
        pageSelectDto.setListPageData(articleDtoList);
    }

    //9.首页推荐回显
    public List<ArticleDto> getArticleIndexList() {
        ArticleExample articleExample = new ArticleExample();
        ArticleExample.Criteria criteria = articleExample.createCriteria();
        criteria.andIsShowEqualTo(YesOrNoEnum.YES.getCode());
        criteria.andStatusEqualTo(StatusEnum.PUBLISH.getCode());
        criteria.andIndexShowEqualTo(PorductIndexShowEnum.SHOW.getCode());
        articleExample.setOrderByClause("sort desc");
        List<Article> articleList = articleMapper.selectByExampleWithBLOBs(articleExample);
        List<ArticleDto> articleDtoList = new ArrayList<>();
        articleList.stream().forEach(article -> {
            List<String> seoKey = Arrays.asList(article.getSeoKeyword().split(";"));
            List<String> picList = Arrays.asList(article.getPicList().split(";"));
            ArticleDto articleDto = DuplicateUtil.copy(article, ArticleDto.class);
            articleDto.setSeoKeyword(seoKey);
            articleDto.setPicList(picList);
            articleDtoList.add(articleDto);

        });

        return articleDtoList;
    }

    //10.新闻中心页面的封面图
    public List<ArticleDto> getArticlePicCover() {
        ArticleExample articleExample = new ArticleExample();
        ArticleExample.Criteria criteria = articleExample.createCriteria();
        criteria.andIsShowEqualTo(YesOrNoEnum.YES.getCode());
        criteria.andStatusEqualTo(StatusEnum.PUBLISH.getCode());
        criteria.andLevelEqualTo(LevelEnum.THREE.getCode());
        List<Article> articleList = articleMapper.selectByExampleWithBLOBs(articleExample);
        List<ArticleDto> articleDtoList = new ArrayList<>();
        articleList.stream().forEach(article -> {
            List<String> seoKey = Arrays.asList(article.getSeoKeyword().split(";"));
            List<String> picList = Arrays.asList(article.getPicList().split(";"));
            ArticleDto articleDto = DuplicateUtil.copy(article, ArticleDto.class);
            articleDto.setSeoKeyword(seoKey);
            articleDto.setPicList(picList);
            articleDtoList.add(articleDto);
        });
        return articleDtoList;
    }

    //获取上下篇文章
    public ArticleDto getArticlePrevious(String uniId) {
        ArticleExample articleExample = new ArticleExample();
        ArticleExample.Criteria criteria = articleExample.createCriteria();
        criteria.andIsShowEqualTo(YesOrNoEnum.YES.getCode());
        criteria.andStatusEqualTo(StatusEnum.PUBLISH.getCode());
        Article art = getTypeId(uniId);
        criteria.andTypeIdEqualTo(art.getTypeId());
        articleExample.setOrderByClause("sort desc");
        List<Article> articleList = articleMapper.selectByExampleWithBLOBs(articleExample);
        List<ArticleDto> articleDtoList = new ArrayList<>();
        ArticleDto articleDto = new ArticleDto();
        articleList.stream().forEach(article -> {
            List<String> seoKey = Arrays.asList(article.getSeoKeyword().split(";"));
            List<String> picList = Arrays.asList(article.getPicList().split(";"));
            ArticleDto articleDto1 = DuplicateUtil.copy(article, ArticleDto.class);
            articleDto1.setSeoKeyword(seoKey);
            articleDto1.setPicList(picList);
            articleDtoList.add(articleDto1);
        });
        for (int i = 0; i < articleDtoList.size(); i++) {
            if (uniId.equals(articleDtoList.get(i).getUniId())) {
                if (i - 1 >= 0) {
                    articleDto = articleDtoList.get(i - 1);
                } else {
                    articleDto = articleDtoList.get(i);
                }

            }
        }
        return articleDto;
    }

    private Article getTypeId(String uniId) {
        Article article = articleMapper.selectByPrimaryKey(uniId);
        return article;
    }

    public ArticleDto getArticleNext(String uniId) {
        ArticleExample articleExample = new ArticleExample();
        ArticleExample.Criteria criteria = articleExample.createCriteria();
        criteria.andIsShowEqualTo(YesOrNoEnum.YES.getCode());
        criteria.andStatusEqualTo(StatusEnum.PUBLISH.getCode());
        Article art = getTypeId(uniId);
        criteria.andTypeIdEqualTo(art.getTypeId());
        articleExample.setOrderByClause("sort desc");
        List<Article> articleList = articleMapper.selectByExampleWithBLOBs(articleExample);
        List<ArticleDto> articleDtoList = new ArrayList<>();
        ArticleDto articleDto = new ArticleDto();
        articleList.stream().forEach(article -> {
            List<String> seoKey = Arrays.asList(article.getSeoKeyword().split(";"));
            List<String> picList = Arrays.asList(article.getPicList().split(";"));
            ArticleDto articleDto1 = DuplicateUtil.copy(article, ArticleDto.class);
            articleDto1.setSeoKeyword(seoKey);
            articleDto1.setPicList(picList);
            articleDtoList.add(articleDto1);
        });
        for (int i = 0; i < articleDtoList.size(); i++) {
            if (uniId.equals(articleDtoList.get(i).getUniId())) {
                if (i + 1 <= articleDtoList.size()) {
                    articleDto = articleDtoList.get(i + 1);
                } else {
                    articleDto = articleDtoList.get(i);
                }

            }
        }
        return articleDto;
    }
}
